<template>
  <div class="mobile-editor-header">
    <div class="history">
      <div class="history-item" :class="{ 'disable': !canUndo }" @click.stop="undo()">
        <IconBack /> 撤销
      </div>
      <div class="history-item" :class="{ 'disable': !canRedo }" @click.stop="redo()">
        <IconNext /> 重做
      </div>
    </div>
    <div class="back" @click="exitEdit()">
      <IconLogout /> 保存编辑
    </div>
  </div>

</template>

<script lang="ts" setup>

import { ref } from "vue";
import { useSlidesStore } from "@/store";
const { slides } = storeToRefs(useSlidesStore());
/**
 * 编辑
 */
import { preservationWorks } from '@/http/api';
import { decryptPpt, encryptPpt } from "@/utils/crypto"
import type { ApiResponse } from '@/http/api'; // 使用 type-only import
const data = ref<ApiResponse | null>(null);

import { storeToRefs } from 'pinia'
import { useSnapshotStore } from '@/store'
import type { Mode } from '@/types/mobile'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'

const props = defineProps<{
  changeMode: (mode: Mode) => void
}>()
const emit = defineEmits(['getData']);
const exitEdit = async () => {
  emit('getData', true)
  const base: any = sessionStorage.getItem("base")
  console.log(base, 'base');
  const baseJson: any = JSON.parse(base)
  let dataPomas = {
    "cmd": "storeWork",
    "base": baseJson,
    "param": {
      "taskId": sessionStorage.getItem("taskId"),
      "text": JSON.stringify(slides.value),
      "traceId": uuid(),
      "userId": baseJson.userid
    }
  }
  console.log(dataPomas);

  let encryptedData = encryptPpt(JSON.stringify(dataPomas), '1058', sessionStorage.getItem("Appid"))
  if (!encryptedData) {
    return
  }
  // console.log(encryptedData);
  // console.log(JSON.stringify(slides.value));

  data.value = await preservationWorks(encryptedData);
  // if (data.value.code !== 200) {
  //   console.log(data.value);
  //   return
  // }
  props.changeMode('preview')
  emit('getData', false)
}

const uuid = (length = 32) => {
  const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  let str = ''
  for (let i = 0; i < length; i++) {
    str += num.charAt(Math.floor(Math.random() * num.length))
  }
  return str
}

const { canUndo, canRedo } = storeToRefs(useSnapshotStore())

const { redo, undo } = useHistorySnapshot()
</script>

<style lang="scss" scoped>
.mobile-editor-header {
  height: 50px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 18px;
  font-size: 13px;
  box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 2;
}

.history {
  display: flex;
  justify-content: center;
  align-items: center;
}

.history-item {
  margin-right: 20px;

  &.disable {
    opacity: .5;
  }
}
</style>